﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class OrderDetails : System.Web.UI.Page
{
    int orderid;
    SqlConnection con = new SqlConnection();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Int32.Parse(Session["orderid"].ToString()) == 0)
        {
            Response.Redirect("Orders.aspx");
        }
        orderid = Int32.Parse(Session["orderid"].ToString());
        txtOrderID.Text = orderid + "";
        con.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

        if (this.IsPostBack == false)
        {
            try
            {
                gvOrderDetails.AutoGenerateSelectButton = true;
                gvOrderDetails.AllowPaging = true;
                gvOrderDetails.PageSize = 20;
                LoadOrderDetails();
               
                
                btnDelete.Enabled = false;
                btnUpdate.Enabled = false;
                btnAdd.Enabled = true;
                btnNew.Enabled = true;
                btnReload.Enabled = false;
                Session["isSelectedOrderDetails"] = false;
            }
            catch (Exception ex)
            {
                throw ex;               
            }
        }
        bool tmp = (bool)Session["isSelectedOrderDetails"];
        //o day pa xet la dung roi ha, nhung con thieu
        if (tmp)
        {
            btnDelete.Enabled = true;
            btnUpdate.Enabled = true;
            ////btnSeeDetail.Enabled = true;

            btnAdd.Enabled = false;
        }
        else
        {
            btnDelete.Enabled = false;
            btnUpdate.Enabled = false;
            btnAdd.Enabled = true;
        }

    }

    void LoadOrderDetails()
    {
        try
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = string.Format("SELECT * FROM Sales.OrderDetails WHERE orderid = {0}", txtOrderID.Text);

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);

            gvOrderDetails.DataSource = dt;
            gvOrderDetails.DataBind();

            getDataSource_Products();
        }
        catch (Exception)
        {

            Response.Write("<script>alert('" + "Fails Page! F5 to Reload" + "')</script>");
        }


    }

    void getDataSource_Products()
    {
        try
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT productid, productname FROM Production.Products";
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds, "Production.Products");
            DataTable dt = ds.Tables["Production.Products"];
            DDLProduct.DataSource = dt;
            DDLProduct.DataValueField = "productid";
            DDLProduct.DataTextField = "productname";
            DDLProduct.DataBind();
        }
        catch (Exception ex)
        {
            
            throw ex;
        }
    }

    void AddOrderDetails()
    {
        try
        {
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "sp_OrderDetails_Insert";

            SqlParameter param = new SqlParameter("@orderid", SqlDbType.Int);
            param.Value = txtOrderID.Text.Trim();
            cmd.Parameters.Add(param);

            param = new SqlParameter("@productid", SqlDbType.Int);
            param.Value = DDLProduct.SelectedValue;
            cmd.Parameters.Add(param);

            param = new SqlParameter("@unitprice", SqlDbType.Money);
            decimal tmp0 = decimal.Parse(txtUnitPrice.Text.Trim());
            if (tmp0 > 0)
            {
                param.Value = tmp0;
            }
            else
            {
                param.Value = 0;
            }
            cmd.Parameters.Add(param);

            param = new SqlParameter("@qty", SqlDbType.SmallInt);
            param.Value = txtQty.Text.Trim();
            cmd.Parameters.Add(param);

            param = new SqlParameter("@discount", SqlDbType.Float);
            param.Value = txtDiscount.Text.Trim();
            cmd.Parameters.Add(param);

            cmd.ExecuteNonQuery();
            Response.Write("<script>alert('" + "Add successful!" + "')</script>");
        }
        catch (Exception ex)
        {

            throw (ex);
        }
        con.Close();

    }
    protected void gvOrderDetails_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
                GridViewRow r = gvOrderDetails.SelectedRow;
                DDLProduct.SelectedValue = r.Cells[2].Text;
                txtQty.Text = r.Cells[4].Text;
                txtUnitPrice.Text = r.Cells[3].Text;
                txtDiscount.Text = r.Cells[5].Text;
                Session["isSelectedOrderDetails"] = true;

                btnDelete.Enabled = true;
                btnUpdate.Enabled = true;

                btnAdd.Enabled = false;
        }
        catch (Exception)
        {
            Response.Write("<script>alert('" + "Can not select" + "')</script>");
        }
    }

    void initData()
    {
        txtOrderID.Text = orderid +"";
        DDLProduct.SelectedIndex = 0;
        txtQty.Text = "";
        txtUnitPrice.Text = "";
        txtDiscount.Text = "";
        
        Session["isSelectedOrderDetails"] = false;

        btnDelete.Enabled = false;
        btnUpdate.Enabled = false;
        
        btnAdd.Enabled = true;
        btnNew.Enabled = true;
    }

    void UpdateOrderDetails()
    {
        try
        {
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "sp_OrderDetails_Update";

            SqlParameter param = new SqlParameter("@orderid", SqlDbType.Int);
            param.Value = orderid;
            cmd.Parameters.Add(param);

            param = new SqlParameter("@productid", SqlDbType.Int);
            param.Value = DDLProduct.SelectedValue;
            cmd.Parameters.Add(param);

            param = new SqlParameter("@unitprice", SqlDbType.Money);
            decimal tmp0 = decimal.Parse(txtUnitPrice.Text.Trim());
            if (tmp0 > 0)
            {
                param.Value = tmp0;
            }
            else
            {
                param.Value = 0;
            }
            cmd.Parameters.Add(param);

            param = new SqlParameter("@qty", SqlDbType.SmallInt);
            param.Value = txtQty.Text.Trim();
            cmd.Parameters.Add(param);

            param = new SqlParameter("@discount", SqlDbType.Float);
            param.Value = txtDiscount.Text.Trim();
            cmd.Parameters.Add(param);

            cmd.ExecuteNonQuery();
            Response.Write("<script>alert('" + "Update successful" + "')</script>");
        }
        catch (Exception ex)
        {
            throw (ex);
        }
        con.Close();
    }

    void DeleteOrderDetails()
    {
        try
        {
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "sp_OrderDetails_Delete";

            SqlParameter param = new SqlParameter("@orderid", SqlDbType.Int);
            param.Value = txtOrderID.Text;
            cmd.Parameters.Add(param);

            param = new SqlParameter("@productid", SqlDbType.Int);
            param.Value = DDLProduct.SelectedValue;
            cmd.Parameters.Add(param);

            cmd.ExecuteNonQuery();
            Response.Write("<script>alert('" + "Delete successful!" + "')</script>");
        }
        catch (Exception ex)
        {
            throw (ex);
        }
        con.Close();
    }

    void SearchOrderDetails()
    {
        try
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;
            if (DDLSearchBy.SelectedIndex == 0)
            {
                cmd.CommandText = string.Format("SELECT a.* FROM Sales.OrderDetails a,(SELECT productid FROM Production.Products "
                + "WHERE productname LIKE '%{0}%') b WHERE a.productid = b.productid AND a.orderid = '{1}'", txtSearch.Text.Trim(), txtOrderID.Text);
            }
            else
            {
                if (DDLSearchBy.SelectedIndex == 1)
                {
                    cmd.CommandText = string.Format("SELECT * FROM Sales.OrderDetails WHERE unitprice = '{0}' AND orderid = '{1}'", txtSearch.Text.Trim(), txtOrderID.Text);
                }
            }
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable("Sales.OrderDetails");
            da.Fill(dt);
            gvOrderDetails.DataSource = dt;
            gvOrderDetails.DataBind();
        }
        catch (Exception ex)
        {
            throw ex;
           
        }
        
    }
    protected void btnNew_Click(object sender, EventArgs e)
    {
        initData();
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        try
        {
            AddOrderDetails();
            LoadOrderDetails();
        }
        catch (Exception)
        {
            Response.Write("<script>alert('" + "Can not Add" + "')</script>");
        }
    }


    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            UpdateOrderDetails();
            LoadOrderDetails();
        }
        catch (Exception)
        {

            Response.Write("<script>alert('" + "Can not Update" + "')</script>");
        }
    }


    protected void btnDelete_Click(object sender, EventArgs e)
    {
        try
        {
            DeleteOrderDetails();
            LoadOrderDetails();
            initData();
        }
        catch (Exception)
        {

            Response.Write("<script>alert('" + "Can not delete" + "')</script>");
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            initData();
            SearchOrderDetails();
            btnReload.Enabled = true;
        }
        catch (Exception )
        {
            Response.Write("<script>alert('" + "Can not search" + "')</script>");
        }
    }


    protected void btnReload_Click(object sender, EventArgs e)
    {
        try
        {
            initData();
            LoadOrderDetails();
            txtSearch.Text = "";
            DDLSearchBy.SelectedIndex = 0;
            btnReload.Enabled = false;
        }
        catch (Exception)
        {

            Response.Write("<script>alert('" + "Can not Reload" + "')</script>");
        }
    }
    protected void gvOrderDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            gvOrderDetails.PageIndex = e.NewPageIndex;
            LoadOrderDetails();
        }
        catch (Exception)
        {
            
            Response.Write("<script>alert('" + "Can not Change Page" + "')</script>");
        }
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
       try 
	{	        
		 Session["orderid"] = 0;
         Response.Redirect("Orders.aspx");
	}
	catch (Exception)
	{
		
		Response.Write("<script>alert('" + "Can not Back" + "')</script>");
	}
    }
}
